﻿#include "TlvProject.h"
#include "../StoreFilePath.h"
#include "TlvPrjModelParser.h"

#include <QFile>
#include <QDebug>

TlvProject::TlvProject(QObject *parent)
    : IStore<TlvPrjModel>{parent}
{
    model().setModelParser(new TlvPrjModelParser());
    // qDebug() << __LINE__ << &model() << model().m_parser->toString(model().data()) << "\n" << model().toString();
    loadRecentProjects();
}

bool TlvProject::open(const QString &prjPath)
{
    if (prjPath.isEmpty()) return false;
    m_prjPath = prjPath;
    m_prjPath = m_prjPath.replace("\\", "/");
    m_recent.removeAll(m_prjPath);
    m_recent.prepend(m_prjPath);
    saveRecent();
    loadProject();
    return true;
}

bool TlvProject::create(const QString &prjPath, const QString& name)
{
    QFile f(prjPath);
    if (!f.open(QIODevice::WriteOnly)) {
        return false;
    }
    auto tmp = model().emptyModelData();
    tmp.name = name;
    f.write(model().toString(tmp).toUtf8());
    f.close();
    return true;
}

bool TlvProject::save()
{
    return saveAs(m_prjPath, model().data().name);
}

bool TlvProject::saveAs(const QString &savePath, const QString& name)
{
    QFile f(savePath);
    if (!f.open(QIODevice::WriteOnly)) {
        return false;
    }
    model().data().name = name;
    f.write(model().toString().toUtf8());
    return true;
}

void TlvProject::removeFromRecent(const QString &prjPath)
{
    m_recent.removeAll(prjPath);
    saveRecent();
}

void TlvProject::removeFromRecent()
{
    removeFromRecent(m_prjPath);
    saveRecent();
}

QString TlvProject::latestProject() const
{
    if (m_recent.length() == 0) return "";
    return m_recent.at(0);
}

QStringList TlvProject::recentProjects() const
{
    return m_recent;
}

void TlvProject::loadRecentProjects()
{
    QFile file(StoreFilePath::recentPrjList());
    if (!file.open(QIODevice::ReadOnly)) return;
    while (!file.atEnd()) {
        QString path = file.readLine().trimmed();
        if (!path.isEmpty()) m_recent << path;
    }
    file.close();
}

void TlvProject::saveRecent()
{
    QFile file(StoreFilePath::recentPrjList());
    if (!file.open(QIODevice::WriteOnly)) return;
    for (auto& path : m_recent) {
        QString line = path + '\n';
        file.write(line.toUtf8());
    }
    file.close();
}

void TlvProject::loadProject()
{
    QFile f(m_prjPath);
    if (!f.open(QIODevice::ReadOnly)) {
        return;
    }
    QByteArray src = f.readAll();
    f.close();
    model().loadFromStr(src);
    if (model().isValid()) {

    } else {
        qWarning() << model().errorString();
    }

}
